package nezumi.gui;

import java.awt.Color;
import java.awt.Component;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.font.FontRenderContext;
import java.awt.font.TextLayout;
import java.awt.geom.Point2D;

import nezumi.Constants;
import nezumi.state.State;

public class TargetGridEntity extends AEntity {

	public TargetGridEntity(State state, Component enclosingComp) {
		super(state, enclosingComp);
	}

	public void draw(Graphics2D g) {

		final double[][][] targetGrid = state.getTargetState().getTargetGrid();
		final int rows = state.getMapState().getHeight();
		final int cols = state.getMapState().getWidth();

		final double height = (double) this.canvasSize.height
				/ (Constants.MAP_HEIGHT / Constants.MAP_GRANULARITY * 2);
		final double width = (double) this.canvasSize.width
				/ (Constants.MAP_WIDTH / Constants.MAP_GRANULARITY * 2);

		final int intheight = (int) Math.round(height);
		final int intwidth = (int) Math.round(width);

		Color oldColor = g.getColor();
		for (int i = 0; i < cols; i++)
			for (int j = 0; j < rows; j++) {

				for (int k = 0; k < Constants.N_TARGETS; k++) {

					final double maxSightings[] = state.getTargetState()
							.getTargetSightings();

					if (targetGrid[k][i][j] > 0) {
						// paint them in a white gradient
						float c = (float) (targetGrid[k][i][j] / maxSightings[k]);
						g.setColor(new Color(c, c, c));

						Point t = this.translatePoint(new Point(i, j));

						g.fillRect((int) Math.round(t.getX() - width / 2),
								(int) Math.round(t.getY() - height / 2),
								intwidth, intheight);
					}
				}
			}

		FontRenderContext frc = g.getFontRenderContext();
		Font f = new Font("Helvetica", Font.BOLD, 14);

		Point2D likelyTargets[] = this.state.getTargetState()
				.getLikelyTargets();
		g.setColor(Color.MAGENTA);

		for (int i = 0; i < Constants.N_TARGETS; i++) {
			TextLayout tl = new TextLayout(String.format("%d", i), f, frc);
			Point loc = this.translatePoint(new Point((int) likelyTargets[i]
					.getX(), (int) likelyTargets[i].getY()));
			tl.draw(g, (float) loc.getX(), (float) loc.getY());
		}
		g.setColor(oldColor);
	}
}
